package com.wars2d.client.graphics.tiledmap;

import java.util.HashMap;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class TiledMapHelper {
	
	SpriteBatch batch = new SpriteBatch();

	TextureAtlas mTilesAtlas = null;
	
	HashMap<Integer, TextureRegion> mGroupRenderers = new HashMap<Integer, TextureRegion>();
	
	int mapWInBlocks	= 0; // in blocks
	int mapHInBlocks	= 0; // in blocks
	
	int mBlockW 	= 32;
	int mBlockH 	= 32;
	
	int mapWInPixels = 0;
	int mapHInPixels = 0;
	
	int[][] mTileMatrix = null;
	
	public TiledMapHelper(FileHandle mapFile, FileHandle atlasFile) {
		
		mTilesAtlas = new TextureAtlas(atlasFile);
		
		Pixmap mMap = new Pixmap(mapFile);
		
		mapWInBlocks 	= mMap.getWidth();
		mapHInBlocks	= mMap.getHeight();
		
		mapWInPixels 	= mapWInBlocks * mBlockW;
		mapHInPixels 	= mapHInBlocks * mBlockH;

//		if (mMap.getFormat() != Format.RGBA8888) {
//			throw new RuntimeException("format must be RGBA8888");
//		}
		
		mTileMatrix = new int[mapHInBlocks][mapWInBlocks];
		
		for (int i = 0; i < mapHInBlocks; ++i) {
			for (int j = 0; j < mapWInBlocks; ++j) {
				int pixel = mMap.getPixel(j, i);
				
				int tileId = pixel >> 24;
			
				if (!mGroupRenderers.containsKey(tileId)) {
					mGroupRenderers.put(tileId, mTilesAtlas.findRegion(String.valueOf(tileId)));
					
					System.out.println("found new tile : " + tileId);
				}
				
				mTileMatrix[i][j] = tileId;
			}
		}
	}
	
	public void render(float camX, float camY, float viewPortW, float viewPortH) {
		int startCol 	= (int) (camX / mBlockW);
		int endCol 		= (int) ((camX + viewPortW) / mBlockW + 1);
		
		if (endCol >= mapWInBlocks) {
			endCol = mapWInBlocks - 1;
		}
		
		if (startCol < 0)
			startCol = 0;
		
		int startRow 	= (int) (camY / mBlockH);
		int endRow		= (int) ((camY + viewPortH) / mBlockH + 1);
		
		if (endRow >= mapHInBlocks) {
			endRow= mapHInBlocks - 1;
		}
		
		if (startRow < 0)
			startRow = 0;
		
		System.out.println("startCol : " + startCol + " startRow : " + startRow + " endCol : " + endCol + " endRow : " + endRow);
		
		batch.begin();
		
		for (int i = startRow; i < endRow; ++i) {
			for (int j = startCol; j < endCol; ++j) {
				batch.draw(mGroupRenderers.get(mTileMatrix[i][j]), camX + j * mBlockW, camY + i * mBlockH);
			}
		}
		
		batch.end();
	}
}
